package com.apobates.jforum.grief.aurl.selector;

import com.apobates.jforum.grief.aurl.core.AUrlMeta;
import com.apobates.jforum.grief.aurl.executor.HClientContext;
import com.apobates.jforum.grief.aurl.executor.HClientExecutor;
import com.apobates.jforum.grief.aurl.executor.HClientResponse;
import java.net.URISyntaxException;
import java.net.URL;

/**
 * 查询AUrlMeta是否可以访问
 */
public class ActiveSelector extends AUrlMetaSelector<HClientResponse<String>> {

    public ActiveSelector(AUrlMeta rawMeta) {
        super(rawMeta);
    }

    @Override
    public HClientResponse<String> getResult() {
        boolean lived = isLived(getRawMeta().toString());
        return lived?HClientResponse.success(200, "keeplive"):HClientResponse.notFound("NotFound");
    }

    public static boolean isLived(String url){
        try {
            return HClientExecutor.head(url, HClientContext.defaultConfig).statusCode().isSuccess();
        }catch (URISyntaxException e){
            throw new IllegalArgumentException("参数不是合法的网址");
        }
    }
}
